package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.dto.TeamMemberDTO;
import com.tju.ocean_ecology_website.dto.TeamQueryDTO;
import com.tju.ocean_ecology_website.dto.TeamRejectDTO;
import com.tju.ocean_ecology_website.entity.Activity;
import com.tju.ocean_ecology_website.entity.Team;
import com.tju.ocean_ecology_website.entity.TeamMember;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.service.TeamService;
import com.tju.ocean_ecology_website.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 志愿队伍管理控制器
 */
@RestController
@RequestMapping("/api")
public class TeamsController {

    @Autowired
    private TeamService teamService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取志愿队伍列表
     *
     * @param queryDTO 查询参数
     * @return 志愿队伍列表
     */
    @GetMapping("/teams")
    public ResponseEntity<ApiResponse<PageResult<Team>>> getTeamList(TeamQueryDTO queryDTO) {
        // 创建队伍筛选条件
        Team teamQuery = new Team();
        if (queryDTO.getName() != null && !queryDTO.getName().isEmpty()) {
            teamQuery.setName(queryDTO.getName());
        }
        if (queryDTO.getStatus() != null) {
            teamQuery.setStatus(queryDTO.getStatus());
        }
        if (queryDTO.getAuditStatus() != null) {
            teamQuery.setAuditStatus(queryDTO.getAuditStatus());
        }
        if (queryDTO.getLeaderId() != null) {
            teamQuery.setLeaderId(queryDTO.getLeaderId());
        }
        
        // 查询队伍数据
        PageRequest pageRequest = queryDTO.toPageRequest();
        Page<Team> teamPage = teamService.queryByPage(teamQuery, pageRequest);
        
        // 创建分页结果
        PageResult<Team> pageResult = PageResult.fromPage(teamPage, queryDTO.getPage());
        
        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取志愿队伍详情
     *
     * @param id 队伍ID
     * @return 队伍详情
     */
    @GetMapping("/teams/{id}")
    public ResponseEntity<ApiResponse<Team>> getTeamDetail(@PathVariable("id") Long id) {
        Team team = teamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }
        
        return ResponseEntity.ok(ApiResponse.success(team));
    }

    /**
     * 添加志愿队伍
     *
     * @param team 队伍信息
     * @return 添加结果
     */
    @PostMapping("/teams")
    public ResponseEntity<ApiResponse<Team>> addTeam(@RequestBody Team team) {
        // 设置默认值
        team.setAuditStatus(0); // 待审核
        team.setMemberCount(0); // 当前成员数量为0
        team.setCreateTime(new Date());
        team.setUpdateTime(new Date());
        
        Team savedTeam = teamService.insert(team);
        
        return ResponseEntity.ok(ApiResponse.success(savedTeam, "添加队伍成功"));
    }

    /**
     * 更新志愿队伍
     *
     * @param id 队伍ID
     * @param team 队伍信息
     * @return 更新结果
     */
    @PutMapping("/teams/{id}")
    public ResponseEntity<ApiResponse<Team>> updateTeam(
            @PathVariable("id") Long id,
            @RequestBody Team team) {
        
        // 查询队伍信息
        Team existingTeam = teamService.queryById(id);
        if (existingTeam == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }
        
        // 设置ID和更新时间
        team.setId(id);
        team.setUpdateTime(new Date());
        
        // 保留原有的审核状态和拒绝原因
        team.setAuditStatus(existingTeam.getAuditStatus());
        team.setRejectReason(existingTeam.getRejectReason());
        
        // 更新队伍
        Team updatedTeam = teamService.update(team);
        
        return ResponseEntity.ok(ApiResponse.success(updatedTeam, "更新队伍成功"));
    }

    /**
     * 删除志愿队伍
     *
     * @param id 队伍ID
     * @return 删除结果
     */
    @DeleteMapping("/teams/{id}")
    public ResponseEntity<ApiResponse<Boolean>> deleteTeam(@PathVariable("id") Long id) {
        // 查询队伍信息
        Team team = teamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }
        
        // 删除队伍
        boolean result = teamService.deleteById(id);
        
        return ResponseEntity.ok(ApiResponse.success(result, result ? "删除队伍成功" : "删除队伍失败"));
    }

    /**
     * 审核通过队伍
     *
     * @param id 队伍ID
     * @return 审核结果
     */
    @PostMapping("/teams/{id}/approve")
    public ResponseEntity<ApiResponse<Team>> approveTeam(@PathVariable("id") Long id) {
        // 查询队伍信息
        Team team = teamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }
        
        // 更新审核状态
        team.setAuditStatus(1); // 已通过
        team.setRejectReason(null); // 清空拒绝原因
        team.setUpdateTime(new Date());
        
        // 更新队伍
        Team updatedTeam = teamService.update(team);
        
        return ResponseEntity.ok(ApiResponse.success(updatedTeam, "审核通过成功"));
    }

    /**
     * 拒绝队伍
     *
     * @param id 队伍ID
     * @param rejectDTO 拒绝信息
     * @return 拒绝结果
     */
    @PostMapping("/teams/{id}/reject")
    public ResponseEntity<ApiResponse<Team>> rejectTeam(
            @PathVariable("id") Long id,
            @Valid @RequestBody TeamRejectDTO rejectDTO) {
        
        // 查询队伍信息
        Team team = teamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }
        
        // 更新审核状态
        team.setAuditStatus(2); // 已拒绝
        team.setRejectReason(rejectDTO.getReason()); // 设置拒绝原因
        team.setUpdateTime(new Date());
        
        // 更新队伍
        Team updatedTeam = teamService.update(team);
        
        return ResponseEntity.ok(ApiResponse.success(updatedTeam, "拒绝队伍成功"));
    }

    /**
     * 获取队伍成员
     *
     * @param id 队伍ID
     * @param page 页码
     * @param pageSize 每页大小
     * @return 成员列表
     */
    @GetMapping("/teams/{id}/members")
    public ResponseEntity<ApiResponse<PageResult<TeamMemberDTO>>> getTeamMembers(
            @PathVariable("id") Long id,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        // 查询队伍信息
        Team team = teamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }
        
        // 查询队伍成员
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<TeamMember> memberPage = teamService.queryTeamMembers(id, pageRequest);
        
        // 构建成员DTO列表
        List<TeamMemberDTO> memberDTOs = new ArrayList<>();
        for (TeamMember member : memberPage.getContent()) {
            // 查询用户信息
            User user = userService.queryById(member.getUserId());
            
            // 构建DTO
            TeamMemberDTO dto = TeamMemberDTO.fromUserAndTeamMember(user, member);
            memberDTOs.add(dto);
        }
        
        // 创建分页结果
        Page<TeamMemberDTO> dtoPage = new PageImpl<>(memberDTOs, pageRequest, memberPage.getTotalElements());
        PageResult<TeamMemberDTO> pageResult = PageResult.fromPage(dtoPage, page);
        
        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取队伍活动
     *
     * @param id 队伍ID
     * @param page 页码
     * @param pageSize 每页大小
     * @return 活动列表
     */
    @GetMapping("/teams/{id}/activities")
    public ResponseEntity<ApiResponse<PageResult<Activity>>> getTeamActivities(
            @PathVariable("id") Long id,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        
        // 查询队伍信息
        Team team = teamService.queryById(id);
        if (team == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "队伍不存在"));
        }
        
        // 查询队伍活动
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<Activity> activityPage = teamService.queryTeamActivities(id, pageRequest);
        
        // 创建分页结果
        PageResult<Activity> pageResult = PageResult.fromPage(activityPage, page);
        
        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }
}
